package org.csu.jpetmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.jpetmanage.mapper.AdminMapper;
import org.csu.jpetmanage.model.*;
import org.csu.jpetmanage.service.AdminService;
import org.csu.jpetmanage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {

//正常账号密码登录的实现

    @Autowired
    public AdminService adminService;

    @Autowired
    public UserService userService;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    Admin admin;

    @Autowired
    HttpSession httpSession;

    //专门用来保存返回信息（是否发送成功）
    String feedback;

    //这里是/index表示跳转到登陆页面
    @RequestMapping ({"/index"})
    public String index(){
        return "loginForm";
    }

    //这里是/表示跳转到大类界面，这里要改一下，改到左边的搜索框里面
    @RequestMapping("/")
    public  String index2(){
        return "loginForm";
    }

    //这里是点击登录按钮直接跳转的方法
    @PostMapping("/login")
    public String queryByUsernameAndPassword ( @RequestParam("code") String code, Model model){
        if (code == ""){
            feedback = "请输入对应的信息！！！！";
            model.addAttribute("feedback",feedback);
            return "loginForm";
        }
        admin =(Admin) httpSession.getAttribute("admin");
        if (admin.getPassword() == null){
            feedback = "用户名或密码错误！";
            model.addAttribute("feedback",feedback);
            return "loginForm";
        }else if ( CheckCode(code)){
            feedback = "验证码错误";
            model.addAttribute("feedback",feedback);
            return "loginForm";
        }else {
            return "redirect:/ManageQueryAll";
        }
    }
    //js异步请求调用该方法，先根据输入的username找到对应的手机号，在后端发送信息，将验证码储存在session里面
    //这里应该储存在redis里面，但是电脑没有安装虚拟机，还暂时不会操作
    @GetMapping("/getCode")
    public void queryByUserNameAndPassword(@RequestParam("username") String username, @RequestParam("password") String password,Model model){
        System.out.println("coming in");
        admin.setUsername(username);
        //这里对从用户来的密码进行加密操作
        password = userService.encrypt(password);
        System.out.println(username);
        System.out.println(password);
        admin.setPassword(password);
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, username).eq(Admin::getPassword, password);
        Admin admin1 = adminService.getOne(queryWrapper);
        model.addAttribute("admin",admin);
        code(admin1.getTelephone());
        httpSession.setAttribute("admin",admin1);
    }

    //判断验证码和输入的值是否相同
    public boolean CheckCode( String result){
        String load = (String) httpSession.getAttribute("code");
        if (load == result){
            return true;
        }
        return false;
    }

    //获取验证码功能（通过输入的用户名以及密码）
    //这里不会注入redis，就先不写,储存的值直接放在session里面保存着
    public String code( String phone){
        String code = RandomNumbers.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        boolean WhetherSend = adminService.send(param,phone);
        if (WhetherSend){
            httpSession.setAttribute("code",code);
            feedback = "发送成功，请输入验证码！！";
        }else{
            feedback = "发送失败，请稍后重试！！";
        }
        return feedback;
    }

    @GetMapping("/adminAdd")
    public String queryAdmin(

            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("name") String name,
            @RequestParam("address") String address,
            @RequestParam("telephone") String telephone,
            @RequestParam("rank") String rank,
            Model model, HttpSession session) {

        /**
         * Id虽然是自增的，但是插入的时候Id却变成了0
         * 所以这里我们必须得写一个逻辑：
         * Id的值要设为当前表中最大的值+1**/
        //先获取当前表中最大的值
      /*  List<Admin> adminList = adminMapper.selectList(null);//查询所有的list记录
        int max = 0;
        for (int i = 0; i < adminList.size(); i++) {
            if (max < adminList.get(i).getId()) {
                max = adminList.get(i).getId();
            }
        }
        max++;
        admin.setId(max);
*/


        //设值
        admin.setPassword(password);
        admin.setName(name);
        admin.setUsername(username);
        admin.setAddress(address);
        admin.setTelephone(telephone);
        admin.setRank(Integer.parseInt(rank));
        adminMapper.insert(admin);
        session.setAttribute("msg", "插入成功");
        return "redirect:/adminManageIndex";

    }
    @GetMapping("/adminManageIndex")
    public String adminIndex(Model model){
        List<Admin> adminList = adminMapper.selectList(null);//查询所有的list记录
        model.addAttribute("adminList",adminList);
        return "adminManageIndex";
    }

    @RequestMapping("/adminDelete")
    public String adminDelete(
            @RequestParam("adminid") int adminid,
            HttpSession session
    ){
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("id",adminid);
        int sum = adminMapper.deleteByMap(hashMap);
        System.out.println("sum is :"+sum);
        if (sum>=1){
            session.setAttribute("msg","删除成功");
        }
        return "redirect:/adminManageIndex";
    }

    @GetMapping("/adminEditAjax")
    @ResponseBody
    public Map<String,Object> adminEditAjax(
            @RequestParam("adminid") int adminid,
            HttpSession session
    ){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",adminid);//是根据admin实体类中的属性来进行取值
        List<Admin> adminList = adminMapper.selectList(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        if (adminList.size()==1){
            System.out.println("adminList size is 1");
            admin = adminList.get(0);
            session.setAttribute("editAdmin",admin);//待会处理编辑数据的时候需要用
            //把下面补全
            map.put("username",admin.getUsername());
            map.put("password",admin.getPassword());
            map.put("userid",admin.getId());
            map.put("name",admin.getName());
            map.put("address",admin.getAddress());
            map.put("telephone",admin.getTelephone());
            map.put("rank",admin.getRank());

            return map;
        }
        return map;
    }

    @RequestMapping("/adminEdit")
    public String adminEdit(

            @RequestParam("editusername") String username,
            @RequestParam("editpassword") String password,
            @RequestParam("editname") String name,
            @RequestParam("editaddress") String address,
            @RequestParam("edittelephone") String telephone,

            Model model, HttpSession session
    ){
        admin = (Admin)session.getAttribute("editAdmin");

        admin.setUsername(username);
        admin.setPassword(password);
        admin.setName(name);
        admin.setAddress(address);
        admin.setTelephone(telephone);


        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",admin.getId());
        int rows = adminMapper.update(admin,updateWrapper);
        System.out.println("Edited rows number is: "+rows);
        session.setAttribute("msg","修改成功");
        return "redirect:/adminManageIndex";
    }

    @RequestMapping("/searchAdmin")
    public String searchItem(
            @RequestParam("keyword") String keyword,
            Model model){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        System.out.println(keyword);
        queryWrapper.like("username",keyword).
                or().like("password",keyword).
                or().like("telephone",keyword).
                or().like("id",keyword).
                or().like("rank",keyword);

        List<Admin> adminList=adminMapper.selectList(queryWrapper);
        model.addAttribute("adminList" ,adminList);
        return "adminManageIndex";
    }

    @GetMapping("/adminSearchAjax")
    @ResponseBody
    public List<Admin> orderSearchAjax(
            @RequestParam("keyword") String keyword,
            HttpSession session){
        System.out.println(keyword+" in OrderController");
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username",keyword).
                or().like("password",keyword).
                or().like("telephone",keyword).
                or().like("rank",keyword);

        return adminMapper.selectList(queryWrapper);
    }
}








